import 'package:fijkplayer/fijkplayer.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:oss_upload/oss_upload.dart';
import 'package:richedit/data/video_entity.dart';
import 'package:richedit/loading_widget.dart';
import 'package:richedit/widget/custom_fijkpanel.dart';

class VideoEdit extends StatefulWidget {
  VideoEntity data;

  VideoEdit(this.data);

  @override
  _VideoEditState createState() => _VideoEditState();
}

class _VideoEditState extends State<VideoEdit> {
  int _uploadCount = 0;
  int _uploadTotal = 0;
  bool _isUpload = false;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () async {
          LoadingWidget.showLoading(context, text: "正在读取文件");
          FilePickerResult? result = await FilePicker.platform.pickFiles(
            type: FileType.video,
          );
          LoadingWidget.dismissLoading();
          if (result == null) {
            return;
          }
          var uploadFile = await OSSUpload.uploadFile(result.files.single.path!, "1", "1", "1", suffix: ".mp4",
              onSendProgress: (int count, int total) {
            _uploadCount = count;
            _uploadTotal = total;
            _isUpload = true;
            setState(() {});
          });
          _isUpload = false;
          if (uploadFile != null) {
            String fileUrl = uploadFile['url'];
            widget.data.url = fileUrl;
            setState(() {});
          }
        },
        child: Container(
          child: widget.data.url == null
              ? Container(
                  width: 80,
                  height: 80,
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.black12, width: 1),
                  ),
                  child: _isUpload
                      ? Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text("${(_uploadCount * 100 / _uploadTotal).toStringAsFixed(1)}%"),
                            Padding(padding: const EdgeInsets.all(4)),
                            Text("正在上传"),
                          ],
                        )
                      : Icon(Icons.ondemand_video),
                )
              : Container(
                  padding: const EdgeInsets.all(1),
                  constraints: BoxConstraints(
                    maxHeight: 300,
                  ),
                  child: RichVideoWidget(widget.data.url!),
                ),
        ),
      ),
    );
  }
}

class VideoPreview extends StatefulWidget {
  VideoEntity data;

  VideoPreview(this.data);

  @override
  _VideoPreviewState createState() => _VideoPreviewState();
}

class _VideoPreviewState extends State<VideoPreview> {

  FijkPlayer player = FijkPlayer();
  double? _vWidth;
  double? _vHeight;
  @override
  void initState() {

    player.addListener(() {
      FijkValue value = player.value;
      double? width ;
      double? height;

      if (value.prepared && value.size != null) {
        width = value.size!.width;
        height = value.size!.height;
      }

      if (width != _vWidth || height != _vHeight) {
        setState(() {
          _vWidth = width;
          _vHeight = height;
        });
      }
    });
    player.setDataSource(widget.data.url!, autoPlay: false, showCover: true);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      constraints: BoxConstraints(
        maxHeight: 300,
      ),
      child: FijkView(
        color: Colors.black,
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.width * ( _vHeight??200 / (_vWidth??MediaQuery.of(context).size.width)),
        panelBuilder: customFijkPanelBuilder,
        player: player,
      ),
    );
  }

  @override
  void dispose() {
    player.release();
    super.dispose();
  }
}


class RichVideoWidget extends StatefulWidget {
  String videoPath;

  RichVideoWidget(this.videoPath);

  @override
  _RichVideoWidgetState createState() => _RichVideoWidgetState();
}

class _RichVideoWidgetState extends State<RichVideoWidget> {
  // VideoPlayerController _videoPlayerController;
  // ChewieController _chewieController;
  FijkPlayer player = FijkPlayer();
  double? _vWidth;
  double? _vHeight = 200;

  @override
  void initState() {

    player.addListener(() {
      FijkValue value = player.value;
      double? width ;
      double? height;

      if (value.prepared && value.size != null) {
        width = value.size!.width;
        height = value.size!.height;
      }

      if (width != _vWidth || height != _vHeight) {
        setState(() {
          _vWidth = width;
          _vHeight = height;
        });
      }
    });
    player.setDataSource(widget.videoPath, autoPlay: false, showCover: true);
    super.initState();
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.center,
      child: FijkView(
        color: Colors.black,
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.width * ( _vHeight??200 / (_vWidth??MediaQuery.of(context).size.width)),
        panelBuilder: customFijkPanelBuilder,
        player: player,
      ),
    );
  }

  @override
  void dispose() {
    player.release();
    super.dispose();
  }
}